
var app = getApp();
const cancelOrder = function(orderNo, shopId){
  return new Promise((resolve, reject) => {
    wx.request({
      url: app.data.global_urls.getCancelOrderUrl(),
      method: 'POST',
      header:{
        'Authorization': `Bearer ${app.data.loginData.token}`,
        'content-type': 'application/x-www-form-urlencoded',
      },
      data:{
        orderNo: orderNo,
        shopId: shopId
      },
      success(res){
        if(10024 === res.data.status){
          // 需要重新登录
          console.log(" inSuccess: 需要重新登录", res)
          app._needReLogin(null, null);
          reject(res);
        }else{
          resolve(res.data);
        }
      },
      fail(e){
        reject(e);
      }
    })
  });
}

const _cancalOrder = function(order, resolve, reject){

  console.log('进入取消订单')
    wx.showToast({
      title: '订单取消中...',
      icon: 'loading',
      duration: 10000,
      mask: true
    })

    cancelOrder(order.orderNo, order.shopId).then((res) => {
      wx.hideToast();
      if(10000 !== res.status){
        // 数据库插入失败，稍后重试
        console.log(" inSuccess: 获取预支付信息失败", res)
        wx.showToast({
          title: '内部服务错误，请稍后再试',
          icon: 'error',
          duration: 3000,
          mask: true
        });
      }else{
        let order = res.data;
        if(order.orderStatus === 0){
          wx.showToast({
            title: '取消成功',
            icon: 'loading',
            duration: 1500,
            mask: true
          })

          if(resolve) resolve(order);
        }else{
          wx.showToast({
            title: '订单取消失败',
            icon: 'loading',
            duration: 1500,
            mask: true
          })
          if(reject) reject(order);
        }
      }
    }).catch((e)=>{
      wx.hideToast();
      wx.showToast({
        title: '订单取消失败',
        icon: 'loading',
        duration: 1500,
        mask: true
      })
      if(reject) reject(e);
    }).finally(()=>{
    })
}

const cancelOrderWithInteractive = function(order){
  let cancelOrderResolve=null;
  let cancelOrderReject=null;

  wx.showModal({
    title: '警告',
    content: '您确定要取消订单吗？',
    cancelText: '是',
    confirmText: '否',
    complete: (res) => {
      if (res.cancel) {
        _cancalOrder(order, cancelOrderResolve, cancelOrderReject);
      }
      if (res.confirm) {
      }
    }
  });

  return new Promise((resolve, reject) => {
    cancelOrderResolve = resolve;
    cancelOrderReject = reject;
  })
}

const addOrderToCart = function(orderDetail, postType){
  let unpay = app.data.globalData.order.unpay;
  let allGoods = app.data.globalData.allGoodsList;
  unpay.id = null
  unpay.postType = postType;
  unpay.goods = []
  orderDetail?.forEach((item) => {
    for(let good of allGoods){
      if(good.id === item.productId){
        good.count = item.quantity;
        unpay.goods.push(JSON.parse(JSON.stringify(good)));
        break;
      }
    }
  })
  
  wx.reLaunch({
    url: '/pages/order/order',
  });
}

const toPayByOrder = function(order, callback){
  wx.request({
    url: app.data.global_urls.getPayByOrderUrl(),
    method: 'POST',
    header:{
      'Authorization': `Bearer ${app.data.loginData.token}`,
      'content-type': 'application/json'
    },
    data:{
      ...order
    },
    success(res){
      wx.hideToast();
      if(10024 === res.data.status){
        // 需要重新登录
        console.log(" inSuccess: 需要重新登录", res)
        app._needReLogin(null, null);
      }else if(10000 !== res.data.status){
        // 数据库插入失败，稍后重试
        console.log(" inSuccess: 获取预支付信息失败", res)
        wx.showToast({
          title: '内部服务错误，请稍后再试',
          icon: 'error',
          duration: 3000,
          mask: true
        });
      }else{
        let prepayArg = res.data.data.prepayWithRequestPaymentResponse;
        if(prepayArg){
          // 获取预支付信息成功
          console.log("获取预支付信息成功，拉起支付", prepayArg)
          app._doPay(prepayArg, callback);
          // app._doPay(prepayArg, null);
        }else{
          wx.showModal({
            title: '提示',
            content: '付款失败，请稍后再试',
            showCancel: false,
            confirmText: '知道了'
          });
        }
      }
    },
    fail(e){
      wx.hideToast();
      wx.showModal({
        title: '提示',
        content: '付款失败，请稍后再试',
        showCancel: false,
        confirmText: '知道了'
      });
    }
  })
  wx.showToast({
    title: '订单提交中',
    icon: 'loading',
    duration: 10000,
    mask: true
  })
}

const orderRefundPromise = function(order){
  let _resolve = null;
  let _reject = null;

  wx.request({
    url: app.data.global_urls.getOrderRefundUrl(),
    method: 'POST',
    header:{
      'Authorization': `Bearer ${app.data.loginData.token}`,
      'content-type': 'application/json'
    },
    data:{
      ...order
    },
    success(res){
      wx.hideToast();
      if(10024 === res.data.status){
        // 需要重新登录
        console.log(" inSuccess: 需要重新登录", res)
        app._needReLogin(null, null);
        _reject(res);
      }else if(10000 !== res.data.status){
        // 数据库插入失败，稍后重试
        console.log(" inSuccess: 订单取消失败", res)
        _reject(res);
        wx.showToast({
          title: '内部服务错误，请稍后再试',
          icon: 'error',
          duration: 3000,
          mask: true
        });
      }else{
        console.log('-------退款申请提交成功--------', res.data)
        _resolve(res.data);
      }
    },
    fail(e){
      _reject(e);
      wx.hideToast();
      wx.showModal({
        title: '提示',
        content: '操作失败，请稍后再试',
        showCancel: false,
        confirmText: '知道了'
      });
    }
  })
  wx.showToast({
    title: '正在提交退款',
    icon: 'loading',
    duration: 10000,
    mask: true
  })

  return new Promise((resolve, reject)=>{
    _resolve = resolve;
    _reject = reject;
  })
}

const cancelRefundPromise = function(order){
  let _resolve = null;
  let _reject = null;

  wx.request({
    url: app.data.global_urls.getCancelRefundUrl(),
    method: 'POST',
    header:{
      'Authorization': `Bearer ${app.data.loginData.token}`,
      'content-type': 'application/json'
    },
    data:{
      ...order
    },
    success(res){
      wx.hideToast();
      if(10024 === res.data.status){
        // 需要重新登录
        console.log(" inSuccess: 需要重新登录", res)
        app._needReLogin(null, null);
        _reject(res);
      }else if(10000 !== res.data.status){
        // 数据库插入失败，稍后重试
        console.log(" inSuccess: 撤销退款失败", res)
        _reject(res);
        wx.showToast({
          title: '内部服务错误，请稍后再试',
          icon: 'error',
          duration: 3000,
          mask: true
        });
      }else{
        console.log('-------撤销退款成功--------', res.data)
        _resolve(res.data);
      }
    },
    fail(e){
      _reject(e);
      wx.hideToast();
      wx.showModal({
        title: '提示',
        content: '操作失败，请稍后再试',
        showCancel: false,
        confirmText: '知道了'
      });
    }
  })
  wx.showToast({
    title: '正在撤销退款',
    icon: 'loading',
    duration: 10000,
    mask: true
  })

  return new Promise((resolve, reject)=>{
    _resolve = resolve;
    _reject = reject;
  })
}

const getAdminHistoryOrder  = function(orderType=-1, pageNo=1, pageSize=10){
  return new Promise((_resolve, _reject)=>{
    wx.request({
      url: app.data.global_urls.getAdminHistoryOrdersUrl(),
      method: 'GET',
      header:{
        'Authorization': `Bearer ${app.data.loginData.token}`,
        'content-type': 'application/x-www-form-urlencoded',
      },
      data:{
        pageNo,
        pageSize,
        orderType
      },
      success(res){
        if(10024 === res.data.status){
          // 需要重新登录
          console.log(" inSuccess: 需要重新登录", res)
          app._needReLogin(null, null);
          _reject(res);
        }else if(10000 !== res.data.status){
          // 数据库插入失败，稍后重试
          console.log(" inSuccess: getAdminHistoryOrder失败", res)
          _reject(res);
          wx.showToast({
            title: '内部服务错误，请稍后再试',
            icon: 'error',
            duration: 3000,
            mask: true
          });
        }else{
          console.log('-------getAdminHistoryOrder成功--------', res.data)
          _resolve(res.data);
        }
      },
      fail(e){
        _reject(e);
        wx.showModal({
          title: '提示',
          content: '操作失败，请稍后再试',
          showCancel: false,
          confirmText: '知道了'
        });
      }
    })
  })
}


const getAdminHistoryOrderV2  = function(orderType=-1, lastIndex, pageSize=10){
  let arg = {
    pageSize,
    orderType
  }
  if(lastIndex){
    arg.lastIndex = lastIndex;
  }
  
  return new Promise((_resolve, _reject)=>{
    wx.request({
      url: app.data.global_urls.getAdminHistoryOrdersV2Url(),
      method: 'GET',
      header:{
        'Authorization': `Bearer ${app.data.loginData.token}`,
        'content-type': 'application/x-www-form-urlencoded',
      },
      data:arg,
      success(res){
        if(10024 === res.data.status){
          // 需要重新登录
          console.log(" inSuccess: 需要重新登录", res)
          app._needReLogin(null, null);
          _reject(res);
        }else if(10000 !== res.data.status){
          // 数据库插入失败，稍后重试
          console.log(" inSuccess: getAdminHistoryOrder失败", res)
          _reject(res);
          wx.showToast({
            title: '内部服务错误，请稍后再试',
            icon: 'error',
            duration: 3000,
            mask: true
          });
        }else{
          console.log('-------getAdminHistoryOrder成功--------', res.data)
          _resolve(res.data);
        }
      },
      fail(e){
        _reject(e);
        wx.showModal({
          title: '提示',
          content: '操作失败，请稍后再试',
          showCancel: false,
          confirmText: '知道了'
        });
      }
    })
  })
}

const finishOrderPromise = function(orderNo){
  return new Promise((resolve, reject)=>{
    wx.request({
      url: app.data.global_urls.getFinishOrderUrl(),
      method: 'POST',
      header:{
        'Authorization': `Bearer ${app.data.loginData.token}`,
        'content-type': 'application/x-www-form-urlencoded',
      },
      data:{orderNo},
      success(res){
        if(10024 === res.data.status){
          // 需要重新登录
          console.log(" inSuccess: 需要重新登录", res)
          app._needReLogin(null, null);
          reject(res);
        }else if(10000 !== res.data.status){
          // 数据库插入失败，稍后重试
          reject(res);
          wx.showToast({
            title: '内部服务错误，请稍后再试',
            icon: 'error',
            duration: 3000,
            mask: true
          });
        }else{
          resolve(res.data);
        }
      },
      fail(e){
        reject(e);
        wx.showModal({
          title: '提示',
          content: '操作失败，请稍后再试',
          showCancel: false,
          confirmText: '知道了'
        });
      }
    })
  })
}

const doRefundAdminPromise = function(orderNo){
  wx.showToast({
    title: '加载中',
    icon: 'loading',
    mask: true,
    duration: 3000
  })
  return new Promise((resolve, reject)=>{
    wx.request({
      url: app.data.global_urls.getDoRefundAdminUrl(),
      method: 'POST',
      header:{
        'Authorization': `Bearer ${app.data.loginData.token}`,
        'content-type': 'application/x-www-form-urlencoded',
      },
      data:{orderNo},
      success(res){
        if(10024 === res.data.status){
          // 需要重新登录
          console.log(" inSuccess: 需要重新登录", res)
          app._needReLogin(null, null);
          reject(res);
        }else if(10000 !== res.data.status){
          // 数据库插入失败，稍后重试
          reject(res);
          wx.showToast({
            title: '内部服务错误，请稍后再试',
            icon: 'error',
            duration: 3000,
            mask: true
          });
        }else{
          resolve(res.data);
        }
      },
      fail(e){
        reject(e);
        wx.showModal({
          title: '提示',
          content: '操作失败，请稍后再试',
          showCancel: false,
          confirmText: '知道了'
        });
      },
      complete(e){
        wx.hideToast();
      },
    })
  })
}

module.exports = {
  cancelOrder,
  cancelOrderWithInteractive,
  finishOrderPromise,
  doRefundAdminPromise,
  addOrderToCart,
  toPayByOrder,
  orderRefundPromise,
  cancelRefundPromise,
  getAdminHistoryOrder,
  getAdminHistoryOrderV2
}